import React, { useState, useEffect, useMemo, useRef } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import {
  Modal,
  Form,
  Button,
  Skeleton,
  Image,
  message,
  Upload,
  Row,
  Col,
  Space,
  Tag,
  Tabs,
  Input,
  List,
  InputNumber,
  Pagination,
} from 'antd'

import {
  ProFormText,
  ProForm,
  ProFormTextArea,
  ProFormSelect,
  ProFormDependency,
  CheckCard
} from '@ant-design/pro-components';

import EditModalAdd from './EditModalAdd'
import PopoverHooks from './PopoverHooks'
// 自拟方
import CustomModalAdd from './CustomModalAdd'



import CheckListButton from '@/components/CheckListButton'

import {
  reqPulseCalibrationList,
  reqTongueCalibrationList,
  reqDiagnosisTermList,
  reqDiagnosisTermListByGrade,
  reqSeniorInquiryList,
  reqSeniorInquiryUpdate,
  reqSymptomList,
  reqSymptomListByGrade,
  reqWesternMedicineList,
  reqBaseFormulaList,
  reqBaseFormulaDetailList,
  reqEtiologyCategoryList,
  reqEtiologyList,
  reqEtiologyCategoryListByDiagnosis,
  reqSeniorInquiryPrescriptionMedication,
  reqBaseFormulaDetailGetBaseFormulaHerb,
  reqAggregationHotDataList
} from '@/services/firstConsultation';



import styles from '../index.module.less'

export default function BaseFormulaList({
  // 用户问诊信息数据
  user,
  closeModal,
}: {
  user: any,
  closeModal: Function,
}) {

  const paginationRef = useRef({
    pageNum: 1,
    pageSize: 20,
    total: 0
  })
  const [data, setData] = useState([])

  const [formObj] = Form.useForm()

  const [seletTyDiagnosisIds, setSeletTyDiagnosisIds] = useState([])

  const [baseFormulaMap, setBaseFormulaMap] = useState(null)
  async function init(query = {}) {
    const errLogName = '汤剂信息列表'
    try {
      const res = await reqBaseFormulaList({ ...query })
      console.log(`${errLogName}信息 :>> `, res?.data);
      if (res?.resultCode == '00000000') {
        paginationRef.current = {
          ...paginationRef?.current,
          total: res?.data?.total
        }
        setData(res?.data?.result)
        let mapObj: any = {};
        res?.data?.result.map((item: any) => {
          mapObj[item.id] = item;
        })
        setBaseFormulaMap(mapObj)
      } else {
        message.error(`${errLogName}信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error(`${errLogName}信息出错！`, error)
      console.log(`${errLogName}信息出错！ :>> `, error);
    }
  }

  const [hotDataList, setHotDataList] = useState()

  async function getHotDataList(query = {}) {
    const errLogName = '常用数据列表'
    try {
      const res = await reqAggregationHotDataList({ ...query })
      console.log(`${errLogName}信息 :>> `, res?.data);
      if (res?.resultCode == '00000000') {

        setHotDataList(res?.data?.result)
      } else {
        message.error(`${errLogName}信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error(`${errLogName}信息出错！`, error)
      console.log(`${errLogName}信息出错！ :>> `, error);
    }
  }


  useEffect(() => {
    init({
      ...paginationRef?.current,
      type: 1
    })
    getHotDataList({
      pageNum: 1,
      pageSize: 10,
      // 类型，[1:中药,2:西药,3:汤剂,4:针灸]
      type: 3
    })
  }, [])



  const onValuesChange = async (params: any) => {
    console.log('onValuesChange=== :>> ', params);

    if (params?.type) {
      setSeletTyDiagnosisIds([])
      const reqData = formObj.getFieldsValue();
      init({
        ...reqData,
        type: params?.type && params?.type[0]
      })
    }

  }


  // 搜索列表
  function onSearchSelect() {
    console.log('onSearchSelect=== :>> ', formObj.getFieldsValue());
    // setSearchKey(value)
    const reqData = formObj.getFieldsValue();
    init({
      ...reqData,
      type: reqData?.type && reqData?.type[0]
    })
  }

  // 类型[1:伤寒经方, 2:方剂学经方, 3:自拟经方,4历史方]
  const optionsList = [
    {
      label: '伤寒经方',
      value: 1
    }, {
      label: '方剂学经方',
      value: 2
    }, {
      label: '自拟经方',
      value: 3
    }, {
      label: '历史方',
      value: 4
    },
  ];


  function arrayFormatOptions(array: []) {
    if (!Array.isArray(array)) return []
    return array.map((item: any) => ({
      label: item?.name,
      title: item?.name,
      value: item?.id,
      size: 'small',
    }))
  }


  // function arrayFormatOptGroup(array: []) {
  //   if (!Array.isArray(array)) return []
  //   return array.map((item: any) => ({
  //     label: item?.parentDiagnosisTerm?.name,
  //     value: item?.parentDiagnosisTerm?.id,
  //     options: arrayFormatOptions(item?.diagnosisTermList)
  //   }))
  // }



  async function onChangeCheckCard(tyDiagnosisIds: any) {
    setSeletTyDiagnosisIds(tyDiagnosisIds.slice(0, 2))
  }

  // 点击汤剂确定按钮
  function onSubmit() {
    if (seletTyDiagnosisIds?.length < 1) {
      message.error('请至少选中一份汤剂！')
      return;
    }
    handleModal(true)
  }


  const [isOpen2, setIsOpen2] = useState(false);

  function handleModal2(bool: boolean) {
    setIsOpen2(bool)
  }


  const [isOpen, setIsOpen] = useState(false);

  function handleModal(bool: boolean) {
    setIsOpen(bool)
  }


  function onShowSizeChange(current: number, pageSize: number) {
    paginationRef.current = {
      ...paginationRef?.current,
      pageNum: current,
      pageSize:pageSize,
    }
    const reqData = formObj.getFieldsValue();
    init({
      ...reqData,
      type: reqData?.type && reqData?.type[0],
      ...paginationRef.current
    });
  }

  return (
    <div>
      <Form
        form={formObj}
        layout="horizontal"
        initialValues={{ type: [1] }}
        onValuesChange={(values): Promise<any> => onValuesChange(values)}
      >
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item name="type" rules={[{ required: true }]}>
              <CheckListButton
                options={optionsList}
                isRadio
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item name="name" >
              <Input.Search
                placeholder="关键字"
                enterButton='搜索'
                onSearch={onSearchSelect}
                onPressEnter={(e) => onSearchSelect(e?.target?.value)}
              />
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <div className={styles.checkCardWrap}>
        <CheckCard.Group
          multiple
          value={seletTyDiagnosisIds}
          onChange={onChangeCheckCard}
        >
          {
            Array.isArray(hotDataList) &&
            (
              formObj.getFieldValue('type') &&
              formObj.getFieldValue('type')[0] != 4
            ) &&
            (
              <>
                <h3>常用汤剂</h3>
                {

                  arrayFormatOptions(hotDataList).map((item, index) => {
                    return (
                      <CheckCard
                        className={styles.checkCard}
                        key={index}
                        title={item?.title}
                        value={item?.value}
                      />
                    )
                  })
                }
              </>
            )
          }

          <h3>汤剂列表</h3>
          {
            Array.isArray(data) &&
            arrayFormatOptions(data).map((item, index) => {
              return (
                <CheckCard
                  className={styles.checkCard}
                  key={index}
                  title={item?.title}
                  value={item?.value}
                />
              )
            })
          }
          {
            formObj.getFieldValue('type') &&
            formObj.getFieldValue('type')[0] == 3 &&
            // <PopoverHooks onSearchSelect={onSearchSelect}>
            <Button icon={<PlusOutlined />} type='primary' onClick={() => handleModal2(true)}>添加自拟方</Button>
            // </PopoverHooks>
          }

        </CheckCard.Group>
        <Pagination
          style={{
            margin: '10px auto'
          }}
          hideOnSinglePage
          current={paginationRef?.current?.pageNum}
          onChange={onShowSizeChange}
          pageSize={paginationRef?.current?.pageSize}
          total={paginationRef?.current?.total}
        />
      </div>
      {/* <Space> */}
      {/* <Button onClick={onSubmit}>配药</Button> */}
      <Button type='primary' onClick={onSubmit}>确定</Button>
      {

        isOpen2 &&
        <CustomModalAdd
          isOpen={isOpen2}
          user={user}
          handleModal={handleModal2}
          closeModal={closeModal}
        />
      }

      {/* </Space> */}
      {
        isOpen &&
        <EditModalAdd
          isOpen={isOpen}
          baseFormulaMap={baseFormulaMap}
          user={user}
          seletTyDiagnosisIds={seletTyDiagnosisIds}
          handleModal={handleModal}
          closeModal={closeModal}
        />
      }
    </div>
  )
}
